<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 19-6-26
 * Time: 下午2:27
 */

namespace api\modules\dict\controllers;


use common\components\tools\Tools;
use common\models\credit_app\BankRate;
use common\models\credit_app\Order;
use common\models\credit_public\SlCity;
use wodrow\yii\rest\ApiException;
use wodrow\yii\rest\Controller;
use yii\db\Expression;

class DefaultController  extends Controller
{
    /**
     * 获取省
     * @desc get
     * @param int $bank_id 贷前银行id
     * @return array
     * @return array provinces 省
     */
    public function actionGetProvinces($bank_id = 0)
    {
        $query = SlCity::find()->andWhere(['display' => 3]);
        if ($bank_id > 0){
            $query->andWhere(new Expression('FIND_IN_SET(:field, admittance_bank)',[':field'=>$bank_id]));
        }
        $provinces = $query->asArray()->all();
        return [
            'provinces' => $provinces,
        ];
    }

    /**
     * 获取金融产品信息
     * @desc get
     * @param string $loan_type 产品
     * @param string $loan_year 时间
     * @param string $bank_id 贷前银行id
     * @param string $province 省:浙江省
     * @param string $is_new_car 车辆新旧类型
     * @param string $o_id 订单id
     * @return array
     */
    public function actionGetBankRate($loan_type, $bank_id, $loan_year, $province = null, $is_new_car, $o_id = null)
    {
        $query = BankRate::find()->where(['rt_type' => $loan_type, 'rt_ylimit' => $loan_year, 'rt_bank_id' => $bank_id, 'rt_status' => 'ok']);
        if ($o_id){
            $order = Order::findOne(['o_id' => $o_id]);
            if ($order && $order->o_bank_time){
                $query->andWhere(['<=', 'rt_up_time', $order->o_bank_time]);
            }
        }
        $bank_rate = $query->one();
        if (!$bank_rate){
            throw new ApiException(201906271111, "未找到相关产品利率");
        }
        $in = in_array($province, Tools::str2arr($bank_rate->bank->bk_inpro))?true:false;
        $br = $bank_rate->toArray();
        $_cfield = $_rfield = "rt_";
        if ($is_new_car == '新车'){
            $_cfield .= "newcode";
            $_rfield .= "newrate";
        }
        if ($is_new_car == '二手车'){
            $_cfield .= "seccode";
            $_rfield .= "secrate";
        }
        if ($in){
            $_cfield .= "_in";
            $_rfield .= "_in";
        }else{
            $_cfield .= "_out";
            $_rfield .= "_out";
        }
        $br['_code'] = $bank_rate->$_cfield;
        $br['_rate'] = $bank_rate->$_rfield;
        $br['_rate'] = $br['_rate']/100;
        return [
            'br' => $br,
        ];
    }
}